<?php

namespace app\admin\model;

use think\Model;

/**
 * Device
 */
class Device extends Model
{
    // 表名
    protected $name = 'device';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 字段类型转换
    protected $type = [
        'timestamp'    => 'timestamp:Y-m-d H:i:s',
        'install_time' => 'timestamp:Y-m-d H:i:s',
    ];
        // 如果需要让level字段总是出现在查询结果中
    protected $append = ['rssi_level'];
    
    protected $createTime = 'timestamp'; // 自定义创建时间字段名
    public function admin(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\Admin::class, 'agent_id', 'id');
    }
    public function merchant(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\Merchant::class, 'merchant_id', 'id');
    }
    public function market(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\Market::class, 'market_id', 'id');
    }
    public function space(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\Space::class, 'space_id', 'id');
    }
    public function getRssiLevelAttr($value, $data)
    {
        $rssi = $data['rssi'] ?? 0;
        // 这里实现你的计算逻辑，例如：
        if ($rssi >= 28) {
            return 5;
        }elseif ($rssi >= 24 && $rssi<28) {
            return 4;
        }elseif ($rssi >= 20 && $rssi<24) {
            return 3;
        }elseif ($rssi >= 16 && $rssi<20) {
            return 2;
        }else{
            return 1;
        }
    }

    // 在插入前自动获取market_id
    protected static function onBeforeInsert($device)
    {
        if (!empty($device->agent_id)) {
            $merchant = $device->admin;
            if($merchant) {
                $device->market_id = $merchant->market_id;
            }
        }
        // if(!empty($device->warranty_day)) {
        //         $device->warranty_effect_time = time() + ($device->warranty_day)*24*60*60;
        // }
        $device->install_time= time();
    }




 
    

}